import Taro from '@tarojs/taro'
import {GOOD_LOAD, GOOD_BASIC, GOOD_GROUP_LIST, GOOD_DETAIL} from '../constants/good'
import { asyncGoodDetail,asyncUsergroupDetail } from '../api/good'
import { asyncGroupInfo } from '../api/group'

// 设置商品基本信息
export const setGoodBasic = data => {
  return {
    type: GOOD_BASIC,
    data
  }
}

// 设置商品的拼购信息
export const setGoodGroup = data => {
  return {
    type: GOOD_GROUP_LIST,
    data
  }
}

// 设置商品详细信息
export const load = (data) => {
  return {
    type: GOOD_LOAD,
    data
  }
}

// 获取拼单商品详细信息 queryAsyncUsergroupDetail
export const groupDetailData = (data) => {
  console.log(data)
  return {
    type: GOOD_DETAIL,
    data
  }
}


// 异步的action 加载商品详细
export function asyncGoodDetailInfo () {
  return (dispatch, getState) => {
    const { token } = getState().user
    const { goodId } = getState().good
    if (!token || !goodId) return // TODO 二者不在的处理

    asyncGoodDetail(token, goodId).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(load(data))
      }
    })
  }
}

// 异步action 加载商品的拼团列表
export function asyncGoodGroup () {
  return (dispatch, getState) => {
    const { token } = getState().user
    const { goodId } = getState().good
    if (!token || !goodId) return // TODO 二者不在的处理

    asyncGroupInfo(token, goodId).then(({data, status}) => {
      console.log('商品拼团信息' + status)
      if (status) {
        dispatch(setGoodGroup({
          group_list_id: Math.floor(Math.random() * 100000),
          group_list: data.list, // 拼团 团list
          group_num: data.group_num, // XX 人成团
          group_total :data.total_num // 已有X人参与拼团
        }))
      }else {
        dispatch(setGoodGroup({
          group_list_id: Math.floor(Math.random() * 100000),
          group_list: [], // 拼团 团list
          //group_num: data.group_num, // XX 人成团
          group_total: data.total_num// 已有X人参与拼团
        }))
      }
    })
  }
}

// 异步action 加载商品的拼团列表
export function asyncgroupDetail (scene_value) {
  return (dispatch, getState) => {
    const { token } = getState().user
     let arrData=scene_value.split("-");
     const user_id = arrData[1]
     const group_code = arrData[0]
    if (!token || !user_id || !group_code) return // TODO 二者不在的处理
    asyncUsergroupDetail(token, user_id, group_code,).then(({data, status}) => {
      if (status) {
        dispatch(groupDetailData(data))
      }else{
        Taro.showToast({
          title: "抱歉您来晚了，该订单已被拼购",
          icon: 'none'
        })
        setTimeout(() => {
          Taro.switchTab({url: '/pages/index/index'})
        }, 1800)
      }
    })
  }
}
